<?php
/**
 * 话题广场相关接口
 */

namespace App\Http\Controllers\App\V3;

use App\Enums\ThemeEnum;
use App\Services\Tools\PushChatService;
use App\Services\Tools\RedisService;
use App\Traits\UserAction;
use App\Jobs\Content\ChatJob;
use App\Enums\ContentTypeEnum;
use App\Enums\ContentNameEnum;
use App\Jobs\Content\ContentJob;
use App\Exceptions\BasicException;
use App\Response\Response;
use App\Services\Tools\FilterService;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;
use Illuminate\Support\Facades\Redis;

class ThemeSquareController extends BaseController
{
    use UserAction;

    public function themeInfo(Request $request)
    {
        $repo = app("repo_theme");

        $themeInfo = $repo->getThemeInfo();

        $user_action_auth = $this->haveUserActionAuth(UID, ContentNameEnum::CHAT_SQUARE);
        $themeInfo['square_auth'] = $user_action_auth;

        return Response::sendData($themeInfo);
    }

    public function striveHeadline(Request $request)
    {
        // 参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'bid_gold' => "required|numeric",
                'content'  => 'required|string',
            ],[
                'content.required'=>"请输入内容"
            ]
        );

        if ($v->fails()) {
            throw new BasicException(10010, getValidateMessage($v->messages()));
        }

        $this->checkUserAction(UID, ContentNameEnum::ROB_HEADLINES);//校验权限

        $params = $request->input();
        $repo = app("repo_theme");
        
        if($params['bid_gold'] != intval($params['bid_gold'])){
            throw new BasicException(10010, '头条金额错误');
        }
        $params['bid_gold'] = intval($params['bid_gold']);
        $baseMoney = $repo->getStriveHeadlineBaseMoney();
        if ($params['bid_gold'] < $baseMoney) {
            throw new BasicException(310001);
        }

        $max_length = 30;
        $msg_code = 310011;
        if (mb_strlen($params['content']) > $max_length) {
            throw new BasicException($msg_code, "内容长度不能大于{$max_length}个字");
        }

        if (FilterService::checkCommon($params['content'], UID, "topics")) {
            throw new BasicException(310007);
        }

        $balance = $repo->striveHeadline(UID, $params['bid_gold'], $params['content']);

        return Response::sendData([
            "user_balance" => $balance,
        ]);
    }

    public function sendChatMsg(Request $request)
    {
        // 参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'theme_id' => 'Required|numeric|exists:mysql.ln_theme,id',
                'type'     => 'required|numeric|in:1',
                'content'  => 'required|string',
            ]
        );

        if ($v->fails()) {
            throw new BasicException(10010, getValidateMessage($v->messages()));
        }
        $this->checkUserAction(UID, ContentNameEnum::CHAT_SQUARE);
        $repo = app("repo_theme");

        $canChatUserRank = $repo->getCanChatUserRank();

        $userRank = app("repo_user")->getUserRank(UID);

        if ($userRank < $canChatUserRank) {
            throw new BasicException(310012);
        }

        $params = $request->input();

        if (FilterService::checkCommon($params['content'], UID, "topics")) {
            throw new BasicException(310007);
        }

        $redisKey = sprintf(ThemeEnum::THEME_SPEAK_COLD_REDIS_KEY, UID);

        $lock = Redis::setnx($redisKey, 1);
        if (!$lock) {
            throw new BasicException(310013);
        }

        Redis::expire($redisKey, ThemeEnum::THEME_SPEAK_COLD_REDIS_KEY_EXPIRE_TIME);

        $chatId = $repo->sendChatMsg(UID, $params['theme_id'], $params['content']);
        //v3.4话题广场发送消息推送聊天公屏
        $userInfo = RedisService::getUserChatLabel(UID,0);

        if (empty($userInfo['special']['chatroom']['material']) && !empty($userInfo['special']['chat']['material'])) {
            $userInfo['special']['chatroom']['material'] = $userInfo['special']['chat']['material'];
        }

        $userInfo['theme_id'] = $params['theme_id'];
        $userInfo['chat_id'] = $chatId;
        $userInfo['title_gift_info'] = app('repo_user')->getUserTitleNowInfo(UID);
        $userInfo['recharge_icon'] = RedisService::getUserRechargeIcon(UID);
        (new PushChatService())->themeStriveChat($params['content'],$userInfo);
        
        $jobData = [
            'user_id'  => UID,
            'key_id'   => $chatId,
            'theme_id' => $params['theme_id'],
            'content'  => $params['content'],
            'content_name' => ContentNameEnum::CHAT_SQUARE,
            'machine_result' => FilterService::$riskLevel,
        ];
        $contentQueueName = env('CONTENT_QUEUE_NAME');
        dispatch(new ChatJob($jobData))->onQueue($contentQueueName);

        return Response::sendData([
            "chat_id" => $chatId,
        ]);
    }

    public function getLastChatMsg(Request $request)
    {
        // 参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'theme_id' => 'Required|numeric|exists:mysql.ln_theme,id',
                'size'     => 'filled|numeric|min:1',
            ]
        );

        if ($v->fails()) {
            throw new BasicException(10010, getValidateMessage($v->messages()));
        }

        $repo = app("repo_theme");

        $params = $request->input();

        $themeId = $params['theme_id'];
        $size = $params['size'] ?? 10;
        if ($size > 100) {
            $size = 100;
        }

        $curTheme = $repo->getCurTheme();
        if ($themeId != $curTheme['id']) {
            throw new BasicException(310002);
        }

        $result = $repo->getLastChatMsg($themeId, $size);

        return Response::sendData($result);
    }

    public function getOldChatMsg(Request $request)
    {
        // 参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'theme_id' => 'Required|numeric|exists:mysql.ln_theme,id',
                'size'     => 'filled|numeric|min:1',
                'start_id' => 'filled|numeric|exists:mysql.ln_theme_chat_log,id',
            ]
        );

        if ($v->fails()) {
            throw new BasicException(10010, getValidateMessage($v->messages()));
        }

        $repo = app("repo_theme");

        $params = $request->input();

        $startId = $params['start_id'] ?? 0;
        $themeId = $params['theme_id'];
        $size = $params['size'] ?? 10;
        if ($size > 100) {
            $size = 100;
        }

        $result = $repo->getOldChatMsg($themeId, $startId, $size);

        return Response::sendData($result);
    }

}
